<?php

// no direct access
defined('_JEXEC') or die;

$lang =& JFactory::getLanguage();
if($lang->getTag() == 'vi-VN')
	$style="style='background: url(./templates/wrd/images/add_card_vi-VN.jpg) no-repeat'";

$session_vipcard =& JFactory::getSession();
$session_vipcard_id =  $session_vipcard->getId();

$item = $this->model;
$lang =& JFactory::getLanguage();

$item->name = unserialize($item->name);
$item->name = $item->name[$lang->getTag()];
$item->des = unserialize($item->des);
$item->des = $item->des[$lang->getTag()];

$quality = $quality_cash = 1;

if(count($this->cookie_items) > 0){
	foreach ($this->cookie_items as $citem){
		if($citem->id == $item->id){
			if($citem->type == 2)
				$quality_cash = $citem->qty;
			if($citem->type == 1)
				$quality = $citem->qty;
		}
		else{
			continue;
		}
	}
}

/*** Check display cash  ***/
$show = false;
if($item->cash > 0):
    $show = true;    
endif;

$page_heading = $item->name;
$title = JText::_('WMCVIP_TITLE_PREFIX').$page_heading.JText::_('WMCVIP_TITLE_SUFIX');
$document = &JFactory::getDocument();
$document->setTitle($title) ;

?>
<link rel="stylesheet" type="text/css" href="<?php echo JURI::base(); ?>js/multiselect/jquery-ui.css" />
<link type="text/css" href="<?php echo JURI::base(); ?>css/buttons.css" rel="stylesheet" />
<script type="text/javascript" src="<?php echo JURI::base(); ?>js/dialog/jquery-ui-1.8.20.custom.min.js"></script>
<script src="<?php echo JURI::base(); ?>js/spin/jquery-spin.js"></script>
<script src="<?php echo JURI::base(); ?>js/jquery.cookie.js"></script>
<script src="<?php echo JURI::base(); ?>js/json_encode.js"></script>
<script src="<?php echo JURI::base(); ?>js/number_format.js"></script>

<link type="text/css" href="<?php echo JURI::base(); ?>templates/wrd/stylesheets/jquery.ad-gallery.css" rel="stylesheet" />
<script src="<?php echo JURI::base(); ?>templates/wrd/javascripts/jquery.ad-gallery.js"></script>
<script type="text/javascript">

     
var scItems = [];
    if(jQuery.cookie("<?php echo md5($session_vipcard_id); ?>") != ""){
        var data_dec = decodeCookies(jQuery.cookie("<?php echo md5($session_vipcard_id); ?>"));
        scItems = json_decode(data_dec);
    }
    
    var currentUserPoint = "<?php echo $this->userPoint; ?>";    
    var totalPointSubtract = currentUserPoint;
    function decodeCookies(obj){
    	var data ;
    	jQuery.ajax({
    		async: false,
            type: "post",
            url : "<?php echo utilitiesProvider::rewriteGlobalUrl('index.php?option=com_promotions&task=decryptcart'); ?>",
            data: "params="+(obj),
            success: function(json){ 
                var result = eval(json);
                
                if (result.success == true)
                {
                	data =  result.data;
                }
                else
                {
                	//console.log('can not decrypt');
                }
            }
        });
        return data;
    }
    jQuery(function(){

    	totalPointAndCash();
        jQuery.spin.imageBasePath = '<?php echo JURI::base(); ?>js/spin/images/spin2/';
        
        jQuery('.spin1').spin({
            max: 100,
            min: 1
        });
        
        jQuery('.spin2').spin({
            max: 100,
            min: 1
        });

        jQuery(".extra-add-to-cart a").click(function(index){  
            /**** Init params ****/
            var objName = jQuery(this).attr("name");
            var item = {
                id:     0,
                qty:    0,
                pcode:  0,
                type:   1,
                img:    '',
                point:  0,
                pointx: 0,
                cash:   0,
                name:   '',
                ptotal: 1
            };
            
            params = objName.split("_");
            item.id = params[1];
            var inputName = jQuery("input[name="+objName+"_type]:checked").attr("id");
            item.type = jQuery("#"+inputName).val();
            
            if(jQuery("input[name="+objName+"_type]:checked").length == 0){
                alert("<?php echo JText::_('WRD_PROFILE_ALERT_PLEASE_CHOOSE_REDEMPTION_TYPE'); ?>");
                return false;
            }
            else {
			
                var qty = jQuery("input[name="+inputName+"_qty]").val();
                
                var productPoint = 0;
                if(item.type == 1) {
                    item.point = jQuery("#"+inputName+"_point").val();  
                    item.cash = 0;
                    item.pointx = 0;
                    productPoint = (parseInt(qty)*parseInt(item.point));
                }
                else {
                    item.point = 0;
                    item.pointx = jQuery("#"+inputName+"_pointx").val();
                    item.cash = jQuery("#"+inputName+"_cash").val();  
                    productPoint = (parseInt(qty)*parseInt(item.pointx));  
                }
                if(qty <= 0){
                    alert("<?php echo JText::_('WRD_PROFILE_ALERT_PLEASE_INPUT_VALID_VALUE'); ?>");
                    jQuery("input[name="+inputName+"_qty]").focus();
                    return false;
                }
                else {
                    var subtractPoint = 0;
                    if(scItems != undefined && scItems.length > 0){
                        for(var i=0; i<scItems.length; i++){
                            if(item.id == scItems[i].id){
                                totalPointSubtract = parseInt(totalPointSubtract) + (parseInt(scItems[i].qty)*parseInt(scItems[i].type == 1 ? scItems[i].point : scItems[i].pointx));
                            }
                        }
                    }
                    var subtractPoint = totalPointSubtract;
                    subtractPoint = parseInt(subtractPoint)-parseInt(productPoint);
                        
                    if(subtractPoint < 0){
                        alert("<?php JText::_('WRD_PROMOTION_YOUR_POINT_IS'); ?> "+(totalPointSubtract)+" < "+productPoint+" <?php echo JText::_('WRD_PROMOTION_IS_NOT_ENOUGHT_TO_REDEEM'); ?>");
                    }
                    else {
                        item.qty = qty;
                        item.img = jQuery("#"+objName+"_img").attr("src");
                        item.pcode = jQuery("#"+objName+"_code").html();
                        item.name = inputName;
						//console.log("#"+objName+"_img"); 	
                      
                        var update = true;
                        var ptotal = 0;
                        var oldqty = 1;
                         if(scItems != undefined && scItems.length > 0){
                            for(var i=0; i<scItems.length; i++){
                                if(scItems[i].id == item.id) {
                                    /*** Roll back point and delete again ***/
                                    if(scItems[i].type != item.type) {
                                       update = false;
                                    }else{
                                    	oldqty = scItems[i].qty;
                                        scItems[i] = item;
                                        update = true;
                                        break;
                                    }
                                   
                                }else{
                                    update = false;
                                }
                                
                            }
                            if(update == false) {
                                scItems.push(item);
                            }
                        }
                        else {
                        	if(scItems ==  null){
                                scItems = new Array();
                                scItems[0] = item;
                            } else {
                                scItems.push(item);
                            }
                            
                        }
                        
                    }
                }
            }   
            
            for(var i=0; i<scItems.length; i++){
                if(scItems[i].id == item.id) {
                    ptotal = ptotal + parseInt(scItems[i].qty);
                }
            }
            
            /*** Process Data ***/
           item.ptotal = ptotal;
            jQuery.ajax({
            	async: false,
                type: "post",
                url : "<?php echo utilitiesProvider::rewriteGlobalUrl('index.php?option=com_promotions&layout=addtocart&view=redemptions'); ?>",
                data: "params="+json_encode(item),
                success: function(json){ 
                    var result = eval(json);
                   	
                    if (result.success == true){

                        totalPointAndCash();
                    }
                    else
                    {
                    	if(result.refresh == true) page_refresh = true;
                    	if(scItems != null && scItems.length > 0){
                            for(var i=0; i<scItems.length; i++){
                                if(scItems[i].id == item.id) {
                                    if(scItems[i].type == item.type){
                                        scItems[i].qty = oldqty;
                                        jQuery("input[name="+scItems[i].name+"_qty]").val(scItems[i].qty);
                                        
                                    }
                                }
                            }
                        }
                        
						if(result.html != '')
                        	alert(result.html);

                    }
                }
            }); 
            
            var data_enc = encodeCookies(scItems);
            jQuery.cookie("<?php echo md5($session_vipcard_id); ?>", json_encode(data_enc), { expires: 1, path: '/' });   
			totalPointAndCash();
			
			if(page_refresh == true){
            	location.reload(true);
            }
            
            return true;
        });

	function encodeCookies(obj){
		var data ;
    	jQuery.ajax({
    		async: false,
            type: "post",
            url : "<?php echo utilitiesProvider::rewriteGlobalUrl('index.php?option=com_promotions&task=encryptcart'); ?>",
            data: "params="+json_encode(obj),
            success: function(json){ 
                var result = eval(json);
                
                if (result.success == true)
                {
                	data =  result.data;
                }
                else
                {
                	//console.log('security hole');
                }
            }
        });
        
        return data;
    }
    
    


    function totalPointAndCash(){
        var totalPoint = 0;
        var totalCash = 0;
        //console.log(scItems);
        if(scItems != undefined && scItems.length > 0){
        	var total_item = 0;
            for(var i=0; i<scItems.length; i++){
                totalPoint = parseInt(totalPoint) + parseInt(scItems[i].point)*parseInt(scItems[i].qty) + parseInt(scItems[i].pointx)*parseInt(scItems[i].qty);
                totalCash = parseInt(totalCash) + parseInt(scItems[i].cash)*parseInt(scItems[i].qty);
                total_item = total_item + parseInt(scItems[i].qty);
            }
            totalPointSubtract = parseInt(currentUserPoint) - parseInt(totalPoint);
            
            var html = "<table style=\"width: 100%;\" cellpadding=\"0\" cellspacing=\"0\"><tbody>";
            html += "<tr><td width=\"60%\" align=\"right\"><strong><?php echo JText::_('WRD_LEFT_MENU_YOUR_POINTS'); ?></strong> </td><td width=\"40%\" align=\"right\">"+number_format(totalPointSubtract, 0,',',',')+"</td></tr>";
            html += "<tr><td width=\"60%\" align=\"right\"><?php echo JText::_('WRD_LEFT_MENU_TOTAL_POINTS'); ?></td><td width=\"40%\" align=\"right\">"+number_format(totalPoint, 0,',',',')+"</td></tr>";
            
            html += "<tr><td align=\"right\"><?php echo JText::_('WRD_LEFT_MENU_TOTAL_CASH'); ?></td><td align=\"right\">"+number_format(totalCash, 0,',',',')+"</td></tr>";
            html += "</tbody></table>";
            
            if(total_item <= 1)
				jQuery("#cart-items").html('<span class="item_count">'+total_item+'</span><span class="item_text"><?php echo JText::_('WRD_LEFT_MENU_ITEM_IN_YOUR_CART')?></span>');
			else
				jQuery("#cart-items").html('<span class="item_count">'+total_item+'</span><span class="item_text"><?php echo JText::_('WRD_LEFT_MENU_ITEMS_IN_YOUR_CART')?></span>');
				            	
            jQuery("#invoice-details").html(html); 
            jQuery("#redeem-now-link").show(); 
        }else{
        	var html = "<table style=\"width: 100%;\" cellpadding=\"0\" cellspacing=\"0\"><tbody>";
            html += "<tr><td width=\"50%\" align=\"right\"><?php echo JText::_('WRD_LEFT_MENU_YOUR_POINTS')?></td><td width=\"50%\" align=\"right\">"+number_format(currentUserPoint, 0,',',',')+"</td></tr>";
            html += "<tr><td width=\"50%\" align=\"right\"><?php echo JText::_('WRD_LEFT_MENU_TOTAL_POINTS'); ?></td><td width=\"50%\" align=\"right\">"+number_format(0, 0,',',',')+"</td></tr>";
            
            html += "<tr><td align=\"right\"><?php echo JText::_('WRD_LEFT_MENU_TOTAL_CASH'); ?></td><td align=\"right\">"+number_format(0, 0,',',',')+"</td></tr>";
            html += "</tbody></table>";
            
			jQuery("#cart-items").html('<span class="item_count">0</span><span class="item_text"><?php echo JText::_('WRD_LEFT_MENU_ITEM_IN_YOUR_CART')?></span>');

            jQuery("#invoice-details").html(html);
            jQuery("#redeem-now-link").hide();
        }
    }

    var galleries = jQuery('.ad-gallery').adGallery();
    });
    
</script>
<div class="row">
	<div class="twelve columns all_reward_header">
		<?php echo $item->name; ?>
	</div>
</div>
<div id="productdetail">
	<div class="product">
		<div class="productleft">
			<div id="gallery" class="ad-gallery">
		      <div class="ad-image-wrapper">
		      </div>
		      <div class="ad-controls">
		      </div>
		      <div class="ad-nav">
		        <div class="ad-thumbs">
		          <?php if($this->gallery != NULL): ?>
				  <ul class="ad-thumb-list">
		          	<?php  foreach ($this->gallery as $key => $value): ?>
		            <li>
		              <a href="<?php echo JURI::base(); ?>wrd/image/<?php echo $value->image; ?>">
		                <img src="<?php echo JURI::base(); ?>wrd/thumb/<?php echo $value->image; ?>" class="image<?php echo $key; ?>">
		              </a>
		            </li>
		            <?php endforeach; ?>
		          </ul>
				 <?php endif;?> 
		        </div>
		      </div>
		    </div>
	    </div>
	    <div class="productright">
	    	<div class="title"><?php echo $item->name; ?></div><br>
	    	<div class="information">
	    		<form>
	    			<div class="row">
		    			<label class="lablel"><?php echo JText::_('WRD_PROMOTION_WAY_CHECK') ?></label>
		    			<span>
		    				<?php if($item->point > 0): ?>
	                        	<input class="way_check" checked="checked" type="radio" name="extra-item_<?php echo $item->id; ?>_type" id="extra-item_<?php echo $item->id; ?>_id" value="1" />
	                       	 	<font class="<?php echo ($item->quantity <= 0) ? "out_of_stock":""  ?>"><?php echo number_format($item->point,0,',',','); ?> <?php echo JText::_('WRD_PROMOTION_POINTS') ?></font>
	                        <?php endif; ?>
	                        <?php if($show == true): ?>
	                        <br>
							<div class="check">
	                        	<input checked="checked" class="way_check" type="radio" name="extra-item_<?php echo $item->id; ?>_type" id="extra-item_<?php echo $item->id ?>_id_2" value="2" />
	                        	<font class="<?php echo ($item->quantity <= 0) ? "out_of_stock":""  ?>"><?php echo number_format($item->pointx,0,',',','); ?> points + <?php echo number_format($item->cash,0,',',','); ?> <?php echo JText::_('WRD_PROMOTION_VND') ?></font>
							</div>
							<?php endif; ?>
						</span>
					</div>
					<div class="row">
						<br>
						<span class="quality"><?php echo JText::_('WRD_PROMOTION_QUANTITY') ?></span>
						
						<span class="pointonly" style="display:<?php echo $show == true ? 'none' : 'inline' ?>">
	                    	<input id="id_qty" type="text" class="spin1" name="extra-item_<?php echo $item->id; ?>_id_qty" value="<?php echo $quality; ?>" />
	                    	<input type="hidden" id="extra-item_<?php echo $item->id ?>_id_point" value="<?php echo $item->point ?>" />
						</span>
						<span class="point_cash" style="display:<?php echo $show == true ? 'inline' : 'none' ?>">
	                   	 	<input id="id_2_qty"  type="text" name="extra-item_<?php echo $item->id ?>_id_2_qty" class="spin2" value="<?php echo $quality_cash; ?>" />
	                   		<input type="hidden" id="extra-item_<?php echo $item->id ?>_id_2_pointx" value="<?php echo $item->pointx ?>" />
	                    	<input type="hidden" id="extra-item_<?php echo $item->id ?>_id_2_cash" value="<?php echo $item->cash ?>" />
                    	</span>
					</div>
                            
                    <label class="giathamkhao"><?php echo JText::_('WRD_PROMOTION_REF_PRICE') ?> <?php echo number_format($item->price,0,',',','); ?> <?php echo JText::_('WRD_PROMOTION_VND') ?></label>                       
                    <?php if($item->quantity == 0): ?>
		     			<div class="fright" style="float: right; color: red;"><b><i>(<?php echo JText::_('WRD_PROMOTION_OUT_OF_STOCK'); ?>)</i></b></div>
		     		<?php else: ?>
	                	<?php if($this->user->id == 0): ?>
				     		<div><a id="submit" <?php echo $style; ?> class="need_login" name="item_<?php echo $item->id; ?>" href="javascript:void(null);"><?php echo JText::_('WRD_PROMOTION_ADD_TO_CART'); ?></a></div>
				     	<?php else: ?>
				     		<div class="extra-add-to-cart"><a <?php echo $style; ?> id="submit" name="extra-item_<?php echo $item->id; ?>" href="javascript:void(null);"><?php echo JText::_('WRD_PROMOTION_ADD_TO_CART'); ?></a></div>
				     	<?php endif;?>
			     	<?php endif; ?>
                    
	    		</form>
	    		<div class="tomtat">
                	<div class="titledetail"><?php echo JText::_('WRD_PROMOTION_PRODUCT_DETAIL'); ?></div>
                    <div class="contenttomtat">
                    	<?php echo $item->des; ?>
                    </div>
                    <img style="display: none"
                          id="extra-item_<?php echo $item->id ?>_img" 
                          alt="<?php echo $item->name ?>" 
                          title="<?php echo $item->name ?>" 
                          src="<?php echo JURI::base().'wrd/image2/'.$item->image; ?>">
                </div>
	    	</div>
	    </div>
	 </div>
</div>
